package com.itany.shop.controller;

import com.itany.mvc.annotation.RequestMapping;
import com.itany.mvc.annotation.ResponseBody;
import com.itany.mybatis.factory.ObjectFactory;
import com.itany.shop.entity.User;
import com.itany.shop.exception.ShopException;
import com.itany.shop.service.UserService;
import com.itany.shop.util.AjaxResult;
import com.itany.shop.util.CommonUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Description: 类的描述
 * Author: liudaolin@itany.com
 * Date: 2021/07/21 15:39
 * Version: 1.0 版本信息
 */
@RequestMapping("/user")
public class UserController {

    @ResponseBody
    @RequestMapping("/register")
    public AjaxResult register(HttpServletRequest request, HttpServletResponse response) {
        AjaxResult ar = new AjaxResult("注册成功", true);

        // 获取参数的值
        String loginName = request.getParameter("loginName");
        String password = request.getParameter("password");
        String rePassword = request.getParameter("rePassword");
        String nickname = request.getParameter("nickname");
        String phone = request.getParameter("phone");

        // TODO: 数据格式验证
        if (CommonUtil.isEmpty(loginName)) {
            ar.setSuccess(false);
            ar.setMsg("用户名不能为空");
            return ar;
        }

        // 数据的封装
        User user = new User();
        user.setLoginName(loginName);
        user.setPwd(password);
        user.setNickname(nickname);
        user.setPhone(phone);
        // 默认数据的设置
        user.setCreateDate(new Date());

        // service
        UserService userService = ObjectFactory.getObj("userService");
        try {
            userService.register(user, rePassword);
        } catch (ShopException e) {
            ar.setSuccess(false);
            ar.setMsg(e.getMessage());
        }
        return ar;
    }


    @ResponseBody
    @RequestMapping("/login")
    public AjaxResult login(HttpServletRequest request, HttpServletResponse response) {
        AjaxResult ar = new AjaxResult("登录成功", true);

        // 登录
        String loginName = request.getParameter("loginName");
        String password = request.getParameter("password");

        User user = new User();
        user.setLoginName(loginName);
        user.setPwd(password);

        UserService userService = ObjectFactory.getObj("userService");
        try {
            userService.login(user);
        } catch (ShopException e) {
            ar.setSuccess(false);
            ar.setMsg(e.getMessage());
        }

        return ar;
    }
}
